<?php

namespace app\index\controller;

use app\admin\library\Auth;
use app\common\controller\Frontend;
use EasyWeChat\Factory;
use app\admin\model\Admin;
use app\common\controller\Api;
use app\admin\model\finance\extract\Week as Planmodel;
use app\admin\model\finance\extract\Weeklog as Planlog;
use app\index\controller\Books;
use app\admin\controller\finance\extract\Week;
use think\Cookie;
//报计划
class Plan extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    public $plan_auth = ['copy_person'=>0,'auditor'=>0,'add'=>0,'department'=>0];

   /**
     * 公共
     * @author gzy
     * @date   2018年8月12日 09:15:00
     */
    public function _initialize(){
        parent::_initialize();
        $Api = new Api();
        //获取默认值
        $this->config = $Api->getConfig($Api->getDefault('Plan'));
        $this->auth = \app\admin\library\Auth::instance();
        $this->model = new Planmodel();
        //退出
        //print_r($this->auth->logout());die; 
        //模拟登陆
         //$this->auth->IndexLogin('GaoZhenYu');
        //判断权限
        //print_r($this->auth->check('see/index'));die;
         if (!$this->auth->isLogin() || (!$this->auth->isLogin() && !ValueExists($this->request->action(),'login,oauth,index'))){
            header("Location:".$this->request->domain().'/index/plan/login');
            //return redirect($this->request->domain().'/index/plan/login');
        }else{
             $this->plan_auth =  check_plan_public(1,$this->auth);
             if(!$this->plan_auth) $this->error(__('请联系管理员'));
             // print_r(date('W',strtotime('2019-11-25')));die;
       
        }
        $start_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['start_time'];
        $end_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['end_time'];
        $this->view->assign("DefaultsTime", $start_time.','.$end_time);
         $this->view->assign("DefaultsDate", date('Y'));
        $this->view->assign("DefaultsDateW", GetYearWeekOne(date('Y'),$start_time)-1);
        $this->view->assign("plan_auth",$this->plan_auth);
       // $this->plan_auth['add'] = 1;
    }

   
    public function index(){
        \think\Cookie::delete("plan_auth");
       $this->auth->logout();
       // 检测是否需要验证登录
       return redirect($this->request->domain().'/index/plan/login');
        
    }  
    public function lists() {
       header('Access-Control-Allow-Credentials:true');
       $this->view->assign('info','');
       if($this->plan_auth['copy_person'] || $this->plan_auth['auditor']){
           $dept_list = \app\admin\model\AuthDepartment::where('id','in',implode(',', GetBaseInfo('Dept')))->select();
           $dept_list = collection($dept_list)->toArray();
           $this->view->assign('dept_list',$dept_list);
       }
       $this->view->assign('status_list',$this->model->getStatusList());

       $this->view->assign('status_tu_list',$this->model->getStatustubiaoList());
       return $this->view->fetch();
    }
    public function lists_ajax(){
       header('Access-Control-Allow-Credentials:true');
        if ($this->request->isAjax()){
            $where = ' 1 = 1';
            $sort = $this->request->get("sort", "start_time");
            $order = $this->request->get("order", "desc");
            $page = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);
            $offset = $limit*$page;
            $time = $this->request->get("time", '');
            $year = $this->request->get("year", '');
            $status = $this->request->get("status", '');
            if($this->plan_auth['copy_person'] || $this->plan_auth['auditor']){
                 $department = $this->request->get("department", 0);
                //判断只能看到自己部门审核失败和草稿的 没部门则看不到
                if($this->plan_auth['department']){
                  $where .= " and (CASE WHEN `status` in (-1,0,1) THEN `department` = '".$this->plan_auth['department']."' ELSE true END)";
                }else{
                   $where .= ' and `status` not in(-1,0,1)';
                }
            }elseif($this->plan_auth['add'] || $this->plan_auth['department']){
                $department = $this->plan_auth['department'];
            }else{
                 $department = 1;
            }
            if($department){
                $where .=' and `department` = '.$department;
            }
            if($status != -3){
                $where .=' and `status` = '.$status;
            }
            if($time){
                $time = explode(',', $time);
                $where .=" and `start_time` = '".$time[0]."' and `end_time` = '".$time[1]."'";
            }
            if($year){
                $where .=" and `year` = '".$year."' ";
            }
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                 ->order($sort, $order)
                 ->limit($offset,$limit)
                ->select();
            foreach ($list as $k => &$v){
                $v['updatetime'] = date('Y-m-d');
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
    }   
    public function add(){
      header('Access-Control-Allow-Credentials:true');
      if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $week = explode(',',$params['week']);
                $params['start_time'] = isset($week[0])?$week[0]:'';
                $params['end_time'] = isset($week[1])?$week[1]:'';
                $params['name'] = date('m.d',strtotime($params['start_time'])).'-'.date('m.d',strtotime($params['end_time']));
                $params['week'] = GetYearWeekOne($params['year'],$week[0]);
                $params['month'] = date('m',strtotime($params['start_time']));
                $empty_info = $this->model->where(array('start_time'=>$params['start_time'],'week'=>$params['week'],'department'=>$this->plan_auth['department']))->find();
              // print_r($this->model->getLastSql());die;
                if($empty_info) $this->error('所选周已经添加过,确定要跳转么？','',$empty_info['id']);
                $params['publish'] = $params['z_publish']  = \think\Session::get('admin')['userid'];
                $params['department'] = $this->plan_auth['department'];
                try {
                    $result = $this->model->save($params);
                    if ($result !== false) {
                       if($params['status'] == 1) check_plan_public(2,$this->auth,$this->model->id);
                       $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    public function edit($ids = NULL){
      header('Access-Control-Allow-Credentials:true');
      $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
      if($row->department != $this->plan_auth['department'] || $row->status>=1) $this->redirect('view',['ids'=>$ids]);
      if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $week = explode(',',$params['week']);
               $params['start_time'] = isset($week[0])?$week[0]:'';
                $params['end_time'] = isset($week[1])?$week[1]:'';
                $params['week'] = GetYearWeekOne($params['year'],$week[0]);
                $params['month'] = date('m',strtotime($params['start_time']));
                $empty_info = $this->model->where(array('start_time'=>$params['start_time'],'week'=>$params['week'],'department'=>$this->plan_auth['department']))->where(" id <> ".$ids)->find();
                if($empty_info) $this->error('所选周已经添加过,确定要跳转么？','',$empty_info['id']);
                $params['z_publish']  = \think\Session::get('admin')['userid'];
                $params['department'] = $this->plan_auth['department'];
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        if($params['status'] == 1){
                              //提交订货单日志
                            // Planlog::create([
                            //     'plan_id'=>$ids,
                            //     'userid'=>$this->auth->userid,
                            //     'dep_id'=>$this->plan_auth['department'],
                            //     'username'=>$this->auth->username,
                            //     'content'=>'已提交报计划,等待审核',
                            //     'action'=>'审批发起',
                            //     'type'=>1,
                            // ]);
                           check_plan_public(2,$this->auth,$ids);
                        }
                       $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row->status == '-1'){
            $log = Planlog::where(['dep_id'=>$row['department'],'extract_week'=>$ids])->select();
            //print_r($log);die;
            $row['log'] = $log;
            //审核页面   所有的数据、
        }
        $this->view->assign('row',$row);
        return $this->view->fetch();
    }
    /**
     * 审核
     */
    public function details($ids = null){
        $plan_info = Planmodel::get($ids);
        if(!$plan_info) $this->error(__('No Results were found'));
        $log = Planlog::where(['dep_id'=>$plan_info['department'],'extract_week'=>$ids])->select();
       
        //print_r($log);die;
        $plan_info['log'] = $log;
        unset($value);
        $userinfo = Admin::get(array('userid'=>$plan_info['publish']));
        //上线就显示
        if($plan_info->status != '1'  || !check_plan_public(3,$this->auth,$ids)){
            //已经结束审核
            $this->redirect('view',['ids'=>$ids]);
        }
        //审核页面   所有的数据、
        $this->view->assign('admin',$this->auth);
        $this->view->assign('userinfo',$userinfo);
   
        $this->view->assign('plan_info',$plan_info);
        return $this->view->fetch();
    }
    /**
     * 审核 通过 驳回 提交
     * @return mixed
     */
    public function do_check_save($ids=null){  
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $plan_info = Planmodel::get($ids);
            if(!$plan_info) $this->error(__('No Results were found'));
           //上线就显示
            if($plan_info->status != '1'  || !check_plan_public(3,$this->auth,$ids)){
                $this->error(__('没有权限'));
            }
            $save = ['content'=>$data['content']];
            //驳回
            if($data['status'] == '-1')
            {
                $save['save'] = 2;
                //驳回
                check_plan_public(3,$this->auth,$ids,$save);
                $this->success();
                
            }
            $save['save'] = 1;
            //发送通知给下一个审核人
            check_plan_public(3,$this->auth,$ids,$save);
           
        }
         $this->success();
       
    }
    public function view($ids = NULL){
        $row = Planmodel::get($ids);
        if(!$row) $this->error(__('No Results were found'));
        $TaskStatus = \app\common\model\task\Outer::getOuter($ids);
          //print_r($row);die;
        $WeekModel = GetWeekModel($row);
        if ($this->request->isPost()) {
            if(isset($WeekModel['Score']['Check']['index']) &&  ($this->plan_auth['department'] == $row['department']) && ($row->status == 2 || $row->status == -2) && $TaskStatus[1]>0 && $TaskStatus[4] == 0){
                $params['z_publish']  = \think\Session::get('admin')['userid'];
                $params['status'] = 3;
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        //通知
                       //check_plan_public(2,$this->auth,$ids);
                       $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }

            }else{
                switch (true) {
                   case $TaskStatus[1]<=0:
                        $msg = '通过审核的任务单不能为0';
                        break; 
                   case $TaskStatus[4]!=0:
                        $msg = '还有审核中的任务单';
                        break;
                    default:
                        $msg = '此数据不能提交';
                        break;
                }
                $this->error($msg);
            }
        }
        $log = Planlog::where(['dep_id'=>$row['department'],'extract_week'=>$ids])->select();
        $row['log'] = $log;
        unset($value);
        $this->view->assign('plan_info',$row);
      
        $this->view->assign("TaskStatus",$TaskStatus);
        $this->view->assign("WeekModel", $WeekModel);
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }
    public function public_view($type = Null,$ids = NULL){
        //GenerateWeek($ids);
       if(empty($ids) || empty($type)) $this->error(__('Parameter %s can not be empty', $ids ? 'ids' : 'type'));
       $WeekInfo = [];
        switch ($type) {
           case 'Books':
               \think\Cookie::delete("books_auth");
               $this->BooksModel = new Books();
               $this->view->assign('ids',$ids);
               return $this->BooksModel->view($ids);
               break;
           case 'User':
                $WeekInfo[$type] =  TableListSqlQuery($type.'Extract',"u.extract_week = '".$ids."'");
               break; 
            case 'Season':
                $WeekInfo[$type] =  TableList($type,$ids,'extract_week',[],'season_time','asc');
               break;
           default:
               $WeekInfo[$type] = TableList($type,$ids,'extract_week');
               break;
       }
       $info = $this->model->get($ids);
       if(!$info) $this->error(__('No Results were found'));
       $this->loadlang('finance.extract.week','admin');
       $this->view->assign('ids',$ids);
       $this->view->assign('type',$type);
       $this->view->assign('WeekInfo',$WeekInfo);
       $this->view->assign('info',$info);
       $WeekModel = GetWeekModel($info);
       $this->view->assign("WeekModel", $WeekModel);
       //print_R($WeekInfo);die;
     //  return $this->view->fetch('plan/'.strtolower($type).'/view');
       return $this->view->fetch('public_view_'.strtolower($type));
      

    }
    /**
     * 通用添加
     */
    public function public_add($type = Null,$ids = NULL,$jump = 0){
         if(!AdminAuth('finance/extract/week/'.strtolower($type).'_add')) $this->error(__('您没有权限'));
        if(empty($ids) || empty($type)) $this->error(__('Parameter %s can not be empty', $ids ? 'id' : 'type'));
        $info = $this->model->get($ids);
        if (!$info) $this->error(__('No Results were found'));
        $true = CheckeWeekStatus($ids);
        if (!$true['status']) $this->error($ture['msg']);
        if ($this->request->isPost()) {
          $params = $this->request->post();
            if ($params) {
                $model = model(GetTableModel($type));
                $params['extract_week']    = $ids;
                $params['publish']    = \think\Session::get('admin')['userid'];
                $params['z_publish']  = \think\Session::get('admin')['userid'];
                if($type == 'Season'){
                    if(!TableField('Admin','userid',$params['lecturer_id'],'userid')) $this->error('讲师不存在');
                }
                if($type == 'User'){
                    if(!TableField('Admin','userid',$params['userid'],'userid')) $this->error('人员不存在');
                    $info = TableField('User','userid',$params['userid'],'userid',['extract_week'=>$ids]);
                    if(!empty($info)) $this->error('本周已存在此人员');
                    if(!empty($params['position'])){
                        $params['position'] = implode(',',$params['position']);
                    }
                }
                try {
                    $result = $model->allowField(true)->save($params);
                    if ($result !== false) {
                         $this->success('操作成功','',$ids);
                    } else {
                        $this->error($model->getError());
                    }

                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("ids",$ids);
        $this->view->assign("jump",$jump);
        $this->view->assign("info",$info);
        $this->view->assign("username",\think\Session::get('admin')['username']);
        $week = new Week();
        $this->loadlang('finance.extract.week','admin'); 
        $WeekInfo = $week->type_info($type,'','',$ids);
        $this->view->assign("WeekInfo",$WeekInfo);
        $this->obtaain();
        if($type == 'Season'){
            $arr = '';
            foreach ($WeekInfo['Subject_id'] as $key => $val) {
                $arr .="{id:'".$val['id']."',value:'".$val['name']."'},";           
            }
           $this->view->assign("arr", trim($arr));
        }
        return $this->view->fetch('public_add_'.strtolower($type));
        
    }
    /**
     * 通用编辑
     */
    public function public_edit($type = Null,$ids = NULL){
        if($type == 'User2'){
            if(!AdminAuth('finance/extract/week/add')) $this->error(__('您没有权限'));
        }else{
            if(!AdminAuth('finance/extract/week/'.strtolower($type).'_edit')) $this->error(__('您没有权限'));
        }
        if(empty($ids) || empty($type)) $this->error(__('Parameter %s can not be empty', $ids ? 'ids' : 'type'));
        if($type == 'Venue_sales'){
            $model = model(GetTableModel('Season'));
        }elseif($type == 'User2'){
            $model = $this->model;
        }else{
            $model = model(GetTableModel($type));
        }
        $row = $model->get($ids);
        if($type == 'User2'){
          $true = CheckeWeekStatus($ids);
        }else{
          $true = CheckeWeekStatus($row->extract_week);
        }
        if (!$true['status']) $this->error($ture['msg']);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params['z_publish']  = \think\Session::get('admin')['userid'];
                   if($type == 'Season'){
                    if(!TableField('Admin','userid',$params['lecturer_id'],'userid')) $this->error('讲师不存在');
                }
                if($type == 'User'){
                    if(!TableField('Admin','userid',$params['userid'],'userid')) $this->error('人员不存在');
                    $info = TableField('User','id',$params['userid'],'userid',['extract_week'=>$ids]);
                    if(!empty($info) && $info != $ids) $this->error('本周已存在此人员');
                    if(!empty($params['position'])){
                        $params['position'] = implode(',',$params['position']);
                    }
                }
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        //添加一轮书信息
                        if($type == 'Venue_sales'){
                            $data = $this->request->post("data/a");
                            if(!empty($data)){
                                $result = model(GetTableModel($type))->where('season_id','=',$id)->delete();
                                model(GetTableModel($type))->saveAll(HandleRound($id,$data));
                            }
                        }
                        if($type == 'User2'){
                            $this->success('操作成功');
                        }else{
                               $this->success('操作成功','',$row->extract_week);  
                        }
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $week = new Week();
        $this->loadlang('finance.extract.week','admin'); 
        $WeekInfo = $week->type_info($type,$ids,$row,$row->extract_week);
        $this->view->assign("WeekInfo",$WeekInfo);
        if($type == 'User'){
           $this->view->assign("department", TableField('Week','department',$row->extract_week,'id'));
        }
        if($type == 'Season'){
            $arr = '';
            $dearr = '';
            foreach ($WeekInfo['Subject_id'] as $key => $val) {
                if($row->subject_id == $val['id']) $dearr = $key;
                $arr .="{id:'".$val['id']."',value:'".$val['name']."'},";           
            }
           $this->view->assign("dearr", $dearr);
           $this->view->assign("arr", trim($arr));
        }
        $this->obtaain();
        //print_R($this->type_info($type,$id,$row,$row->extract_week));die;
        $this->view->assign("row", $row);
        
        return $this->view->fetch('public_edit_'.strtolower($type));
    }
     /**
     * 通用删除
     * @param  int    $id  
     * @param  arr    $type  所拥有权限模块
     * @return array
     * @author gzy
     * @date   2018年8月31日 11:00:00
     */
    public function public_delete($type = Null,$ids = NULL){
         if(!AdminAuth('finance/extract/week/'.strtolower($type).'_delete')) $this->error(__('您没有权限'));
        if(empty($ids) || empty($type)) $this->error(__('Parameter %s can not be empty', $ids ? 'id' : 'type'));
        $model = model(GetTableModel($type));
        $row = $model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($ids) {
            $pk = $model->getPk();
            $list = $model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                //删除学校信息
                if($type == 'School'){
                    $result = model(GetTableModel($type.'_data'))->where('extract_school','=',$ids)->delete();
                }
                $this->success('删除成功');
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    public function obtaain(){
          $app = Factory::work($this->config);
         // $app->jssdk->setUrl("http://oa.fc62.com");
          $json = $app->jssdk->buildConfig(array('checkJsApi','selectEnterpriseContact','openEnterpriseChat','getLocation'));
          $this->view->assign("json", $json);
    }
    public function login(){
        $app = Factory::work($this->config);
        $token = $app->access_token->getToken();//获取企业微信token
        $code = $this->request->request('code');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
        $user = \fast\Http::get($url);
        if(!empty($user)) $user = json_decode($user,true);
        
        if($user['errcode'] == 0){
            if(isset($user['UserId'])){
                if(!$this->auth->IndexLogin($user['UserId'])){
                    $this->error(__('您的账户不存在，请联系管理员'));
                }else{
                    //print_r(\think\Session::get('admin')['userid']);die;
                    return redirect($this->request->domain().'/index/plan/lists');
                }
            }
        }else{
            return redirect($this->request->domain().'/index/plan/oauth');
        }
    }
   public function oauth(){
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->config['corp_id']."&redirect_uri=".$this->config['oauth']['callback']."&response_type=code&scope=".$this->config['oauth']['scopes']."&agentid=".$this->config['agent_id']."&state=STATE#wechat_redirect";
        return redirect($url);
    }

  

}
